home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 4164 < prev    next >
Encoding:
Internet Message Format  |  1996-08-06  |  2.1 KB

  1. Path: news1.h1.usa.pipeline.com!usenet
  2. From: grantp@usa.pipeline.com(Pete)
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: dynamic memory allocation
  5. Date: 28 Jan 1996 15:40:36 GMT
  6. Organization: Kalevi, Inc.
  7. Message-ID: <4eg5dk$5i3@news1.usa.pipeline.com>
  8. NNTP-Posting-Host: pipe4.h1.usa.pipeline.com
  9. X-PipeUser: grantp
  10. X-PipeHub: usa.pipeline.com
  11. X-PipeGCOS: (Pete)
  12. X-Newsreader: Pipeline USA v3.3.0
  13.  
  14. On Jan 28, 1996 00:04:25 in article <dynamic memory allocation>, 'Luciano
  15. Brocchieri <luciano@gnomic.stanford.edu>' wrote: 
  16.  
  17.  
  18. >From main I am passing a pointer int *p to a function function(p,&n) 
  19. >which allocates memory to it: 
  20. >p=(int *)malloc(n,sizeof(int)); 
  21. >My problem is: how do I let main know of the existence of the 
  22. >allocated memory? My solution is writing in main: 
  23. >p=(int *)realloc(p,n*sizeof(int)); 
  24. >right after the function call, before something else gets written 
  25. >on it, which, though effective, doesn't seem very elegant. Besides,  
  26. >functions like malloc(), strdup(), etc., seem to be able to let  
  27. >the calling function know of the allocated memory. What is the  
  28. >right procedure? Any suggestion will be greatly appreciated.  
  29. >Thanks a lot, 
  30. Not quite clear on the constraints involved, also, the question 
  31. is posted to comp.lang.c++ but looks like this might be a straight 
  32. C project??? 
  33.  
  34. Anyway, in either language, it would be preferable to return 
  35. the pointer to the newly allocated memory; e.g., 
  36.  
  37. int * function(int n) 
  38.  { 
  39.     int * p = malloc(n * sizeof(int)); 
  40.     ... dowhateverelse 
  41.     return p; 
  42.  } 
  43. Of course, if you are writing C++ , the first line should read: 
  44.   int * p = new int[n]; 
  45.  
  46. Then, in your calling routine you can just call 
  47.   int * array = function(500); 
  48.  
  49. Now, if you want function to return some other value and 
  50. still want to get at the pointer to the memory allocated, in 
  51. C it's something like: 
  52.  
  53. int function(int n, int ** p) 
  54.  { 
  55.    *p = malloc(n * sizeof(int)); 
  56.    return whatever; 
  57.  } 
  58.  
  59. and in calling routine: 
  60.  
  61.   int * buffer; 
  62.   int x = function(500, &buffer); 
  63.  
  64. C++ solution is similar -- you can use the C way in both. 
  65. -- 
  66. Pete Grant 
  67. Kalevi, Inc. 
  68. Object Oriented Software Development
  69.